package com.bwie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bwie.config.R;
import com.bwie.pojo.User;
import com.bwie.service.UserService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @Auther:${涛}
 * @Date:2024/9/2 09:25
 * @Description: UserController
 * @Version 1.0.0
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @PostMapping("/login")
    public R login(@RequestBody User user) {

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, user.getUsername());


        User oneUser = userService.getOne(wrapper);


        if (oneUser == null) {
            return R.ERROR(404, "账号错误");
        }

        if (!oneUser.getPassword().equals(user.getPassword())) {
            return R.ERROR(404, "密码错误");
        }

        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "bwie").claim("id", oneUser.getId()).claim("roleId", oneUser.getRoleId()).compact();

        stringRedisTemplate.opsForValue().set("token:" + oneUser.getId(), token, 2, TimeUnit.MINUTES);

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("token", token);
        return R.OK(hashMap);
    }
}


